package com.yxw.bamboo.core;

import com.mysql.jdbc.CharsetMapping;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.sql.SQLException;

public class BytesHelper {


    /**
     * 向字节数组中写入long 类型值占4byte
     * @param byteBuffer
     * @param i
     * @param position
     * @throws SQLException
     */
   public static void writeLongInt(byte[] byteBuffer,int i,int position) throws SQLException {
        byte[] b = byteBuffer;
        b[position++] = (byte) (i & 0xff);
        b[position++] = (byte) (i >>> 8);
        b[position++] = (byte) (i >>> 16);
    }


    /**
     * 判断长度并且返回将要写入字节中的长度
     * @param length
     * @return
     * @throws SQLException
     */
   public static int writeFieldLength(long length) throws SQLException {
        if (length < 251) {
           return 1;
        } else if (length < 65536L) {
          return 3;
        } else if (length < 16777216L) {
          return 4;
        } else {
           return 9;
        }
    }

    /**
     * 将字节码写入磁盘
     * @param datas
     * @param destFileName
     */
    public static void writeByteArrayToFile(byte[] datas, String destFileName) {
        // 文件输出流（需要关闭）
        OutputStream os = null;
        try {
            // 字节数组输入流（不需要关闭）
            InputStream is = new ByteArrayInputStream(datas);
            os = new FileOutputStream(new File(destFileName));

            byte[] buf = new byte[1024];
            int len;
            while (((len = is.read(buf)) != -1)) {
                os.write(buf, 0, len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] fileToBinArray(File file){
        try {
            InputStream fis = new FileInputStream(file);
            byte[] bytes = FileCopyUtils.copyToByteArray(fis);
            return bytes;
        }catch (Exception ex){
            throw new RuntimeException("transform file into bin Array 出错",ex);
        }
    }

    //判断一个byte数值在另外一个byte数组中对应的游标值，指定开始的游标和结束的游标位置
    public static int getByteIndexOf(byte[] sources, byte[] src, int startIndex, int endIndex) {

        if (sources == null || src == null || sources.length == 0 || src.length == 0) {
            return -1;
        }

        if (endIndex > sources.length) {
            endIndex = sources.length;
        }

        int i, j;
        for (i = startIndex; i < endIndex; i++) {
            if (sources[i] == src[0] && i + src.length < endIndex) {
                for (j = 1; j < src.length; j++) {
                    if (sources[i + j] != src[j]) {
                        break;
                    }
                }

                if (j == src.length) {
                    return i;
                }
            }
        }
        return -1;
    }


    public static byte[]bigLittleCovert(byte[] byts)
    {
        byte[] tempBytes=new byte[byts.length];
        System.arraycopy(byts,0,tempBytes,0,tempBytes.length);
        if(tempBytes.length%2==0)
        {
            int j=0;
            for(int i=0;i<tempBytes.length;i++)
            {
                j=i+1;
                 byte temp=tempBytes[i];
                tempBytes[i]=tempBytes[j];
                tempBytes[j]=temp;
                i=j;
            }
        }
        return tempBytes;
    }

    public static byte[] toUCS16(String str) {
        if (str == null) {
            return new byte[0];
        } else {
            int strLength = str.length();
            byte[] doubleStrWith0= new byte[strLength * 2];
            int index = 0;

            for(int i = 0; i < strLength; ++i) {
                char currentChar = str.charAt(i);
                byte hChar = (byte)(currentChar & 255);
                doubleStrWith0[index++] = hChar;
                doubleStrWith0[index++] = (byte)(currentChar >> 8 & 255);
            }

            return doubleStrWith0;
        }
    }

    /**
     * 以大端模式将byte[]转成int
     */
    public static int bytesToIntBig(byte[] src, int offset) {
        int value;
        value = (int) (((src[offset] & 0xFF) << 24)
                | ((src[offset + 1] & 0xFF) << 16)
                | ((src[offset + 2] & 0xFF) << 8)
                | (src[offset + 3] & 0xFF));
        return value;
    }

    /**
     * 以小端模式将byte[]转成int
     */
    public static int bytesToIntLittle(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8)
                | ((src[offset + 2] & 0xFF) << 16)
                | ((src[offset + 3] & 0xFF) << 24));
        return value;
    }

    /**
     * 以小端模式将byte[]转成int
     */
    public static long bytesToLongLittle(byte[] src, int offset) {
        long value;
        value = (long) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8)
                | ((src[offset + 2] & 0xFF) << 16)
                | ((src[offset + 3] & 0xFF) << 24)
                | ((src[offset + 4] & 0xFF) << 32)
                | ((src[offset + 5] & 0xFF) << 40)
                | ((src[offset + 6] & 0xFF) << 48)
                | ((src[offset + 7] & 0xFF) << 56));
        return value;
    }
    /**
     * 以小端模式将byte[]转成int
     */
    public static short bytesToShortLittle(byte[] src, int offset) {
        short value;
        value = (short) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8));
        return value;
    }

}
